﻿using System;
using System.Diagnostics;
using System.Threading;

using Moe.ECamel.Common.Contracts;
using Moe.ECamel.Common.Entities;
using Moe.ECamel.Common.Security;
using Moe.ECamel.Client.ServiceProxies;

namespace Moe.ECamel.Client.Controllers
{
	public class SystemController
	{
		private LoginResponse _currentLoginInfo;

		public bool IsLoggedIn
		{
			get { return _currentLoginInfo != null; }
		}
		public LoginResponse CurrentLoginInfo
		{
			get { return _currentLoginInfo; }
		}

		public ECamelSystemInfo LoadSystemInfo()
		{
			using (var serviceProxy = new SystemServiceProxy())
			{
				return serviceProxy.GetSystemInfo();
			}
		}

		public ECamelError Login(String username, String password)
		{
			byte[] hashedPassword = ECamelPasswordHasher.ComputeHash(password);
			
			// Authenticate credentials against database:
			LoginResponse loginResponse;
			using (var serviceProxy = new SystemServiceProxy())
			{
				loginResponse = serviceProxy.Login(new LoginRequest {Username = username, HashedPassword = hashedPassword});
			}

			// Update login state:
			UpdateLoginState(loginResponse.LoginError == null ? loginResponse : null);

			return loginResponse.LoginError;
		}
		public void Logout()
		{
			UpdateLoginState(null);
		}

		private void UpdateLoginState(LoginResponse loginResponse)
		{
			_currentLoginInfo = loginResponse;
			Thread.CurrentPrincipal = loginResponse != null ? new ECamelPrincipal(loginResponse) : ECamelPrincipal.Empty;
		}

		public TimeSpan DeleteUserData()
		{
			Stopwatch sw = Stopwatch.StartNew();

			using (var serviceProxy = new SystemServiceProxy())
			{
				serviceProxy.DeleteUserData();
			}

			sw.Stop();
			return sw.Elapsed;
		}

		public ECamelError ChangeCurrentUserPassword(int userId, String oldPassword, String newPassword)
		{
			using (var serviceProxy = new UserServiceProxy())
			{
				byte[] oldHashedPassword = ECamelPasswordHasher.ComputeHash(oldPassword);
				byte[] newHashedPassword = ECamelPasswordHasher.ComputeHash(newPassword);
				return serviceProxy.ChangeUserPassword(userId, oldHashedPassword, newHashedPassword);
			}
		}
	}
}
